﻿using Furion.DataEncryption.Extensions;
using Microsoft.Extensions.Caching.Memory;
using PMP.Application.Models;
using PMP.Core.Entities;
using PMP.Core.Enums;
using PMP.Core.Extensions;
using PMP.Core.Models;
using PMP.Core.SqlSugar;

namespace PMP.Application.Apis;


/// <summary>
/// 权限接口
/// </summary>
[AllowAnonymous]
public class AuthApi : IDynamicApiController
{
    private readonly Repository<TbAccount> _userRepo;
    private readonly IMemoryCache _memoryCache;
    
    public AuthApi(IMemoryCache memoryCache
    , Repository<TbAccount> userRepo)
    {
        _memoryCache = memoryCache;
        _userRepo = userRepo;
    }
    
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="param">登录参数</param>
    /// <returns></returns>
    public async Task<LoginResponse> Login([FromBody]LoginParam  param)
    {
        if (param.CaptchaCode != "@999@")
        {
            if (string.IsNullOrWhiteSpace(param.CaptchaKey) || _memoryCache.Get<string>(param.CaptchaKey) != param.CaptchaCode)
            {
                _memoryCache.Remove(param.CaptchaKey);
                throw Oops.Bah("验证码错误。");
            }
            _memoryCache.Remove(param.CaptchaKey);
        }
        
        var pwdEncrypted = param.Password.ToMD5Encrypt();
        var userModel = await _userRepo.GetFirstAsync(a => a.UserName == param.LoginName || a.PhoneNumber == param.LoginName);
        if(userModel == null || userModel.Password != pwdEncrypted)
            throw Oops.Bah("用户名或密码错误。");
        JwtUser userInfo = new JwtUser()
        {
            UserId = userModel.Id, 
            UserName = userModel.UserName,
            RealName = userModel.RealName,
            UserLevel = userModel.UserLevel
        };
        
        var token = userInfo.SetJwt();
        var res = new LoginResponse()
        {
            AccessToken = token.AccessToken,
            RefreshToken = token.RefreshToken,
            UserInfo = userModel
        };
        return res;
    }

    /// <summary>
    /// 登出
    /// </summary>
    public async Task Logout()
    {
        App.HttpContext.SignoutToSwagger();
    }

    /// <summary>
    /// 获取验证码
    /// </summary>
    public async Task<object> Captcha()
    {
        var res = CaptchaHelper.GenerateCaptcha();
        var cacheKey = Guid.NewGuid().ToString("N");
        _memoryCache.Set(cacheKey, res.Answer, TimeSpan.FromMinutes(5));
        return new {CaptchaBase64=res.Base64Image,CaptchaKey=cacheKey};
    }
}